<?php
//I.F. Nuevo: 2011-04-25; ramarin

/**
 * shortdesc (optional)
 *
 * longdesc
 *
 * @uses $CFG
 * @param string $sort ?
 * @param string $dir ?
 * @param int $categoryid ?
 * @param int $categoryid ?
 * @param string $search ?
 * @param string $firstinitial ?
 * @param string $lastinitial ?
 * @returnobject {@link $USER} records
 * @todo Finish documenting this function
 */

function get_workflows_listing($get = true, $viewUsers = false, $sort='fullname', $dir='ASC', $page=0, $recordsperpage=0,
                           $search='', $firstinitial='', $lastinitial='', $extraselect=array()) {

    global $CFG, $USER;
    
    if (!isset($extraselect['sqlcondition'])) { $extraselect['sqlcondition'] = ''; }
    if (!isset($extraselect['statecondition'])) { $extraselect['statecondition'] = ''; }
    if (!isset($extraselect['countstatecondition'])) { $extraselect['countstatecondition'] = 0; }

    $LIKE      = sql_ilike();
    $fullname  = sql_fullname();
    
    $systemcontext = get_context_instance(CONTEXT_SYSTEM);
    
    $select = '1';
    
    if(!has_capability('report/moosisca:viewallworkflow', $systemcontext)){
        $select = "mw.userid = " . $USER->id;
    }

    if (!empty($search)) {
        $search = trim($search);
        $select .= " AND ($fullname $LIKE '%$search%' OR email $LIKE '%$search%' OR username='$search') ";
    }

    if ($firstinitial) {
        $select .= ' AND firstname '. $LIKE .' \''. $firstinitial .'%\' ';
    }

    if ($lastinitial) {
        $select .= ' AND lastname '. $LIKE .' \''. $lastinitial .'%\' ';
    }

    if (!empty($extraselect['sqlcondition'])) {
        $select .= " AND " . $extraselect['sqlcondition'];
    }
    
    $select = ltrim($select, ' AND');

    if ($sort) {
        $sort = ' ORDER BY '. $sort .' '. $dir;
    }
    
    $sUser = '';
    
    if($viewUsers){
        $sUser = ", CONCAT(u.firstname, ' ', u.lastname) AS realname";
    }

    if (!$get) {
        if ($extraselect['countstatecondition'] > 0) {
            $sSelect = "SELECT mw.id ";
        }
        else {
            $sSelect = "SELECT COUNT(*) ";
        }
    }
    else {
        $sSelect = "SELECT mw.*, c.fullname {$sUser} ";
    }
    
    $sSelect .= " FROM {$CFG->prefix}course c
                    INNER JOIN {$CFG->prefix}moosisca_workflow mw ON c.id = mw.courseid ";

    if($viewUsers){
        $sSelect .= "INNER JOIN {$CFG->prefix}user u ON u.id = mw.userid ";
    }
    
    if ($extraselect['countstatecondition'] > 0) {
        if (!$get) {
            $sSelect = "SELECT COUNT(*) FROM (SELECT DISTINCT tmp_workflow.id FROM (" . $sSelect . " WHERE $select) AS tmp_workflow LEFT JOIN 
                    {$CFG->prefix}moosisca_workflow_history AS mwh ON tmp_workflow.id = mwh.workflowid WHERE " . $extraselect['statecondition'] .
                    " GROUP BY mwh.workflowid HAVING COUNT(*) >= " . $extraselect['countstatecondition'] . ") AS res";
        }
        else {
            $sSelect = "SELECT DISTINCT tmp_workflow.* FROM (" . $sSelect . " WHERE $select $sort) AS tmp_workflow LEFT JOIN 
                    {$CFG->prefix}moosisca_workflow_history AS mwh ON tmp_workflow.id = mwh.workflowid WHERE " . $extraselect['statecondition'] .
                    " GROUP BY mwh.workflowid HAVING COUNT(*) >= " . $extraselect['countstatecondition'];
        }
    }
    else {
        $sSelect = $sSelect . " WHERE $select $sort";
    }
    
    if ($get) {
        return get_records_sql($sSelect, $page, $recordsperpage);
    } else {
        return count_records_sql($sSelect, $page, $recordsperpage);
    }
} 

function get_history_workflow($select = "mwh.id, c.fullname", $where, $sort='mwh.timecreated', $dir='ASC', $page=0, $recordsperpage=0) {

  global $CFG;

  if ($sort) {
      $sort = ' ORDER BY '. $sort .' '. $dir;
  }

  return get_recordset_sql("SELECT $select
                            FROM {$CFG->prefix}moosisca_workflow_history mwh
                              INNER JOIN {$CFG->prefix}user u ON u.id = mwh.userid
                           WHERE $where $sort", $page, $recordsperpage);
}

function observation_print_attachments($workflow) {

    global $CFG;

    $filearea = observations_file_area_name($workflow->id);

    $imagereturn = "";

    if ($basedir = $CFG->dataroot . '/' . $filearea) {
        if ($files = get_directory_list($basedir)) {
            $strattachment = get_string("attachment", "forum");
            foreach ($files as $file) {
                if($file == $workflow->attachment){
                    $icon = mimeinfo("icon", $file);
                    $type = mimeinfo("type", $file);
                    $ffurl = get_file_url("$filearea/$file");
                    $image = "<img src=\"$CFG->pixpath/f/$icon\" class=\"icon\" alt=\"\" />";

                    if (in_array($type, array('image/gif', 'image/jpeg', 'image/png'))) {    // Image attachments don't get printed as links
                        $imagereturn .= "<br /><img src=\"$ffurl\" alt=\"\" />";
                    } else {
                        echo "<a href=\"$ffurl\" target='_blank'>$image</a> ";
                        echo filter_text("<a href=\"$ffurl\" target='_blank'>$file</a><br />");
                    }
                }
            }
        }
    }

    return $imagereturn;
}

function observations_file_area_name($workflowid) {
    if(!empty($workflowid)){
        return SITEID . '/moosisca/observations/' . $workflowid . '/';
    }
    
    return "";
}

function print_observations($observations) {
    global $CFG;
    
    require_once($CFG->libdir . '/filelib.php');

    foreach($observations as $observation){    
        $user = get_record('user', 'id', $observation['userid']);
        
        echo '<table cellspacing="0" class="forumpost blogpost blog'.$observation["timecreated"].'" width="100%">';
        echo '<tr class="header"><td class="picture left">';
        print_user_picture($user, SITEID, $user->picture);
        echo '</td>';

        echo '<td class="topic starter"><div class="subject"></div><div class="author">';
        $by = new object();
        $by->name =  $observation["realname"];
        $by->date = userdate($observation["timecreated"]);
        print_string('bynameondate', 'forum', $by);
        echo '<tr><td class="left side">';
        echo '</td><td class="content">'."\n";
        
        if (isset($observation["attachment"])) {
            echo '<div class="attachments">';
            $attachedimages = observation_print_attachments((object)$observation);
            echo '</div>';
        } else {
            $attachedimages = '';
        }    

        // Print message
        echo $observation["observations"];

        /// Print attachments
        echo $attachedimages;

        echo '</td></tr></table>'."\n\n";
    }
}

function moosisca_get_spaces_types(){
    $spaceTypes = array();
    $spaceTypes['R'] = get_string('spaceType.Repository', 'report_moosisca');
    $spaceTypes['S'] = get_string('spaceType.SupportToClass', 'report_moosisca');
    $spaceTypes['B'] = get_string('spaceType.Blended', 'report_moosisca');
    
    return $spaceTypes;
}
?>
